package com.xxl.interceptor;

import com.xxl.util.ConstantField;
import com.xxl.util.JwtUtil;
import com.xxl.util.ModelData;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 用户拦截器
 *
 * @author xxl
 * @date 2023/4/4
 */
@Component
public class AuthenticationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies1 = request.getCookies();
        if (cookies1 != null) {
            //使用Stream技术查看是否有服务器存放的cookie，如果有就说明用户是登录的情况并且设置了记住我共功能，没有则是未登录
            List<Cookie> cookies = Arrays.stream(cookies1)
                    .filter(cookie -> cookie.getName()
                            .equals(ConstantField.USER_COOKIE_NAME) ).toList();
            //不为空且大小大于1，就放行
            if (cookies.size() > 0 && !cookies.get(0).getValue().isEmpty()) {
                //用密钥解析token，固定的密钥的隐患就是退出登录换下个账户登录但是还是有户上个账户的权限
                String value = cookies.get(0).getValue();
                JwtUtil.parseJwt(value);
                return true;
            }
        }
        String token = (String) request.getSession().getAttribute(ConstantField.USER_COOKIE_NAME);
        //不为空，且等于服务器保存的cookie值，就放行
        if (token != null && token.equals(ModelData.USER_TOKEN)) {
            return true;
        }
        //为空就重定向并且，提示登录
        response.sendRedirect(request.getContextPath() + "/noAuth/NoAuthentication");
        return false;
    }
}
